package utils

import (
	"database/sql"
	"strings"
	"time"
)

const (
	TimeFormat = "2006-01-02 15:04:05"
	NilTimeStr = "0000-00-00 00:00:00"
)

func GetDateByString(timeStr string) (time.Time, error) {
	loc, err := time.LoadLocation("Asia/Shanghai") //设置时区
	if err != nil {
		loc = time.FixedZone("CST", 8*3600)
	}
	return time.ParseInLocation(TimeFormat, timeStr, loc)
}

func CompareTime(startTime string, endTime string) bool {
	loc, _ := time.LoadLocation("Asia/Shanghai") //设置时区
	start, _ := time.ParseInLocation(TimeFormat, startTime, loc)
	end, _ := time.ParseInLocation(TimeFormat, endTime, loc)
	if end.Unix()-start.Unix() > 0 {
		return true
	} else {
		return false
	}
}

// TimeToString time.Time转string
func TimeToString(t time.Time) string {
	if t.IsZero() {
		return NilTimeStr
	}
	return t.Format(TimeFormat)
}

func GetNowTime() time.Time {
	now := time.Now().Format(TimeFormat)
	ts, _ := GetDateByString(now)
	return ts
}

// format 格式为 Y-m-d H:i:s PHP的时间格式，可以根据需要进行选择需要时间或日期
func TimeFormatRss(t time.Time, format string) string {
	format = strings.Replace(format, "Y", "2006", 1)
	format = strings.Replace(format, "m", "01", 1)
	format = strings.Replace(format, "d", "02", 1)
	format = strings.Replace(format, "H", "15", 1)
	format = strings.Replace(format, "i", "04", 1)
	format = strings.Replace(format, "s", "05", 1)
	return t.Format(format)
}

// 校验时间是否小于当前时间
func TimeBefore(t1 string) bool {
	time1, _ := GetDateByString(t1)
	return time1.Before(time.Now())
}

// 校验验证码是否过期：超过10分钟即过期
func VerifyCodeExpire(t time.Time) bool {
	nowTimeStamp := time.Now()
	if nowTimeStamp.Unix()-t.Unix() > 600 {
		return true
	} else {
		return false
	}
}

func StringToSqlTime(timeStr string) sql.NullTime {
	res := sql.NullTime{}
	if timeStr == "" {
		return res
	}
	layout := "2006-01-02 15:04:05"
	t, _ := time.ParseInLocation(layout, timeStr, time.Local)
	res.Time = t
	res.Valid = true
	return res
}
